import { loginAPI, getUserInfoAPI, getUserInfoByIdAPI } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setTime,
  removeTime
} from '@/utils/auth'
import { Message } from 'element-ui'
import { resetRouter } from '@/router/index'

const state = {
  token: getToken() || null, // token
  userInfo: {} // 用户信息
}

const mutations = {
  // 存入 token
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime()
  },
  // 删除 token
  removeToken(state) {
    state.token = null
    removeToken()
    removeTime()
  },
  // 存入用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 清理用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async LOGIN(store, params) {
    const result = await loginAPI(params)
    store.commit('setToken', result)
  },
  // 获取用户信息
  async GET_USER_INFO(store) {
    const result = await getUserInfoAPI()
    const { staffPhoto } = await getUserInfoByIdAPI(result.userId)
    await store.commit('setUserInfo', { ...result, staffPhoto })
  },
  // 退出登录
  LOGOUT(store) {
    // 删除信息
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
    Message.info('退出登录')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
